<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab" type="border-card">
			<el-tab-pane label="基本信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<!-- 快速选择：从已有物料SKU中复制信息 -->
						<el-row :gutter="20">
							<el-col :span="24" class="mb20">
								<el-form-item label="（正常场景）快速选择物料" label-width="200px">
									<WtmMaterialSelector
										v-model="quickSelectSkuId"
										placeholder="可选：选择已有物料SKU快速填充表单"
										label-format="{MaterialName}({MaterialCode}) - {SkuName}({SkuCode})"
										returnResultFields="Material"
										@change="handleQuickSelect"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="24" class="mb20">
								<el-form-item label="（采购场景）快速选择物料" label-width="200px">
									<WtmMaterialSelector
										v-model="quickSelectMaterialId"
										placeholder="可选：选择已有物料SKU快速填充表单"
										label-format="{MaterialName}({MaterialCode}) - {SkuName}({SkuCode})"
										:isPurchaseScenario="true"
										:showMaterialApplyTab="true"
										:showMaterialSkuApplyTab="true"
										:showSkuListSelect="true"
										@change="handleQuickSelect"
									/>
								</el-form-item>
							</el-col>
						</el-row>

						<el-divider content-position="left">基本信息</el-divider>

						<el-row :gutter="20">
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '名称为必填项', trigger: 'blur' }]">
									<template #label>
										<WtmLabelTooltip label="名称" tooltip="物料名称" />
									</template>
									<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_Code_FormItem" prop="Entity.Code">
									<template #label>
										<WtmLabelTooltip label="编码" tooltip="物料唯一编码，用于系统内标识物料" />
									</template>
									<el-input v-model="stateData.vmModel.Entity.Code" clearable class="width100"></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_MaterialGroupId_FormItem" prop="Entity.MaterialGroupId">
									<template #label>
										<WtmLabelTooltip label="分类" tooltip="物料所属分类" />
									</template>
									<el-select v-model="stateData.vmModel.Entity.MaterialGroupId" clearable class="width100">
										<el-option v-for="item in stateData.AllSysMaterialGroups" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
									></el-select>
								</el-form-item>
							</el-col>

							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_State_FormItem" prop="Entity.State" :rules="[{ required: true, message: '状态为必填项', trigger: 'blur' }]">
									<template #label>
										<WtmLabelTooltip label="状态" tooltip="物料当前状态（启用/禁用等）" />
									</template>
									<el-select v-model="stateData.vmModel.Entity.State" clearable class="width100">
										<el-option key="启用" value="启用" label="启用"></el-option>
										<el-option key="禁用" value="禁用" label="禁用"></el-option
									></el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="12" class="mb20">
								<el-form-item ref="Entity_UnitId_FormItem" prop="Entity.UnitId">
									<template #label>
										<WtmLabelTooltip label="计量单位" tooltip="物料计量单位信息" />
									</template>
									<el-select v-model="stateData.vmModel.Entity.UnitId" clearable class="width100">
										<el-option v-for="item in stateData.AllSysMeasureUnits" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
									></el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="24" class="mb20">
								<el-form-item ref="Entity_Description_FormItem" prop="Entity.Description">
									<template #label>
										<WtmLabelTooltip label="详情" tooltip="物料详细描述信息" />
									</template>
									<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Description" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :lg="24" class="mb20">
								<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
									<template #label>
										<WtmLabelTooltip label="备注" tooltip="计量单位组的备注信息" />
									</template>
									<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Remark" clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="物料SKU列表" name="skus" v-if="stateData.vmModel.Entity.ID"
				><SysMaterialSku :search-bar="false" :toolbar="false" :is-disabled="true" :entity-id="stateData.vmModel.Entity.ID"
			/></el-tab-pane>

			<el-tab-pane label="物料属性列表" name="attributes" v-if="stateData.vmModel.Entity.ID"
				><SysMaterialAttribute :search-bar="false" :toolbar="false" :is-disabled="true" :entity-id="stateData.vmModel.Entity.ID"
			/></el-tab-pane>
		</el-tabs>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysMaterialApi as api } from '/@/views/supplychain/sysmaterial/api';
import other from '/@/utils/other';
import { ISysMaterialVm } from '/@/views/supplychain/sysmaterial/api/interface';
import { IViewModel } from '/@/types/common';
import SysMaterialSku from '/@/views/supplychain/sysmaterialsku/index.vue';
import SysMaterialAttribute from '/@/views/supplychain/sysmaterialattribute/index.vue';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const activeTab = ref('main');
const quickSelectSkuId = ref<string | null>(null);
const quickSelectMaterialId = ref<string | null>(null);
const stateData = reactive<IViewModel<ISysMaterialVm>>({
	vmModel: {
		Entity: {
			Name: null,
			Code: null,
			MaterialGroupId: null,
			Description: null,
			State: '启用',
			UnitId: null,
			Remark: null,
			MaterialId: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysMaterialGroups: [],
	AllSysMeasureUnits: [],
});

/**
 * 处理快速选择物料 - 从已有物料中复制信息
 * @param value - 物料ID 或 SKU ID
 * @param data - 根据 returnResultFields 返回不同的数据结构：
 *   - Material 模式：{ material, attributeIds, attributes, attributesText }
 *   - Sku 模式：{ Entity, Material, Unit, ... }
 *
 * 🎯 使用场景：创建相似物料时，可以从现有物料快速复制信息，然后修改
 */
const handleQuickSelect = (value: string | null, data: any) => {
	if (data) {
		console.log('📦 快速选择的数据 (原始):', data);
	} else {
		// 清空选择时不清空表单，避免误操作
		console.log('🔄 已清空物料选择');
	}
};

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});
const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysMaterial/GetSysMaterialGroups', [], false).then((x) => (stateData.AllSysMaterialGroups = x)),
		other.getSelectList('/api/SysMaterial/GetSysMeasureUnits', [], false).then((x) => (stateData.AllSysMeasureUnits = x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
